package wsi.input;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.rygh.core.util.UIo;
import org.rygh.core.xml.XmlBuilder;
import org.rygh.core.xml.XmlLeaf;
import org.rygh.core.xml.XmlParser;
import org.rygh.core.xml.XmlTree;
import org.rygh.semantic.gui.swing.input.Input;
import org.rygh.semantic.model.rdf.Fact;
import org.rygh.semantic.sparql.SparQL;

import wsi.script.AppConfig;

public class DegreeCandidatePool {

	private final List<Input> inputs = new ArrayList<>();
	private final SparQL query;
	private final int size;

	public DegreeCandidatePool(SparQL query, int size) {
		this.query = query;
		this.size = size;
	}

	public void add(Input input) {
		inputs.add(input);
	}

	public void add(List<Input> list) {
		inputs.addAll(list);
	}

	public File getFile() {
		String fname = query.getCacheFilename(size);
		return new File(AppConfig.shared().getFeedbackInputsFolder(), fname);
	}

	public List<Input> getInputs() {
		return inputs;
	}

	public boolean load() {
		File file = getFile();

		if (!file.exists())
			return false;

		XmlParser parser = new XmlParser(UIo.readFile(file));
		XmlTree tree = parser.parse();

		if (!parser.isValid())
			return false;

		List<XmlLeaf> nodes = tree
				.getNodesByXPath("/feedback_selector/inputs/input");

		for (XmlLeaf n : nodes) {
			Input input = new Input(n.getValue());
			inputs.add(input);
		}

		return true;
	}

	public void save() {
		XmlBuilder xb = new XmlBuilder("feedback_selector");

		xb.begin("query");

		for (Fact f : query.getFacts()) {
			xb.begin("fact");
			xb.escape(f.toString());
			xb.end("fact");
		}

		xb.end("query");

		xb.begin("inputs", "size", inputs.size());

		for (Input i : inputs)
			xb.append(i.toXmlObject().toXmlString());

		xb.end("inputs");

		xb.end();

		UIo.saveFile(getFile(), xb.toString());
	}
}
